<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\AddCartRequest;
use App\Models\ProductSku;
use App\Services\CartService;
use Illuminate\Http\Request;

class CartController extends Controller
{
    protected $cartService;

    public function __construct(CartService $cartService)
    {
        $this->cartService = $cartService;
    }

    // 添加商品到购物车
    public function add(AddCartRequest $request)
    {
        $this->cartService->add($request->input('sku_id'), $request->input('amount'));
        return $this->success('保存商品到购物车成功');
    }

    // 修改购物车里的商品数量
    public function edit(AddCartRequest $request)
    {
        $this->cartService->edit($request->input('sku_id'), $request->input('amount'));
        return $this->success('修改商品到购物车成功');
    }

    // 购物车列表
    public function index()
    {
        $cart = $this->cartService->get();
        return $this->success($cart);
    }

    // 把商品移除购物车
    public function remove(ProductSku $productSku)
    {
        $this->cartService->remove($productSku->id);
        return $this->message('移除商品成功');
    }

    public function destroy(Request $request)
    {
        $this->cartService->remove($request->input('id'));
        return $this->message('移除商品成功');
    }

    // 获取购物车商品数量
    public function cartNum(CartService $cartService)
    {
        $cartNum = $cartService->count();
        return $this->success($cartNum);
    }
}
